package com.result.demo.global.advice;

import com.alibaba.fastjson.JSON;
import com.result.demo.global.annotation.ResponseResult;
import com.result.demo.global.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * @author chao.z
 */
@Slf4j
@RestControllerAdvice
public class ResponseResultAdvice implements ResponseBodyAdvice {


    public static final String RESPONSE_RESULT_ANN = "RESPONSE-RESULT-ANN";

    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes != null ? servletRequestAttributes.getRequest() : null;
        // 判断请求是否有包装标记
        ResponseResult responseResultAnn = (ResponseResult) (request != null ? request.getAttribute(RESPONSE_RESULT_ANN) : null);

        return responseResultAnn != null;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        log.info("进入返回提重写格式 处理中。。。。。。");
        Result result = new Result();
        // 包含Result 说明是异常

        if (body instanceof Result) {
            return body;
        }
        if (body instanceof String) {
            String str = JSON.toJSONString(Result.success(body));
            return str;
        }
        return Result.success(body);
    }

}
